package Cn.edu.zafu.bigdata.x.cxy;

import java.io.*;
import java.net.*;

public class UDPTimeServer {
    public static void main(String[] args) {
        try {
            // 创建一个DatagramSocket在指定端口上监听
            DatagramSocket serverSocket = new DatagramSocket(4567);
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];

            System.out.println("UDP Time Server is running...");

            while (true) {
                // 接收客户端请求
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);

                // 获取客户端的IP地址和端口号
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                // 获取当前系统时间
                String currentTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());

                // 发送时间给客户端
                sendData = currentTime.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
                serverSocket.send(sendPacket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}